package com.gf.common.util;

import java.security.MessageDigest;

/**
 * 将相应的字符串转换为MD5
 * @author zhuguifeng
 *
 */
public class MessageDigester {
	private  static final char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6',
			'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
	 private static MessageDigest mdTemp=null;
	
	 private static MessageDigester md = new MessageDigester();

	
	static{
		try {
			mdTemp = MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	 
	 
	 
	 public static MessageDigester getDigester(){
		 return md;
	 }
	
	/**
	 * 转换
	 * 返回转换后的MD5
	 */
	public String strToMD5(String input) {

		try {
			byte[] strTemp = input.getBytes();
			// 使用MD5创建MessageDigest对象
			mdTemp.update(strTemp);
			
			byte[] md = mdTemp.digest();
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			
			for (int i = 0; i < j; i++) {
				byte b = md[i];
				// System.out.println((int)b);
				// 将每个数(int)b进行双字节加密
				str[k++] = hexDigits[b >> 4 & 0xf];
				str[k++] = hexDigits[b & 0xf];
			}
			
			return new String(str);
			
		} catch (Exception e) {
			e.printStackTrace();
			return null; //转换不成功刚返回null
		}

	}
}
